package com.linked.store.util;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author :dbq
 * @date : 2023/3/23 9:55
 * @description : desc
 */
@Slf4j
public class PdfUtils {

    public static void main(String[] args) throws Exception {

        //需要添加水印的文件
        String inputFile = "D:\\data\\doc\\2021-12-15\\百强县分析报告1639532278835.pdf";
        //添加完水印的文件存放路径
        String outputFile = "D:\\data\\doc\\2021-12-15\\百强县分析报告1639532278835（水印）.pdf";
        //需要添加的水印文字
        String waterMarkName = "添加水印";
        //水印字体透明度
        float opacity = 0.3f;
        //水印字体大小
        int fontsize = 40;
        //水印倾斜角度（0-360）
        int angle = 30;
        //数值越大每页竖向水印越少
        int heightDensity = 50;
        //数值越大每页横向水印越少
        int widthDensity = 10;

        PdfUtils.addWaterMark(inputFile, outputFile, waterMarkName, opacity, fontsize, angle, heightDensity, widthDensity, false);
    }


    /**
     * pdf添加水印
     *
     * @param inputFile     需要添加水印的文件
     * @param outputFile    添加完水印的文件存放路径
     * @param waterMarkName 需要添加的水印文字
     * @param opacity       水印字体透明度
     * @param fontsize      水印字体大小
     * @param angle         水印倾斜角度（0-360）
     * @param heightDensity 数值越大每页竖向水印越少
     * @param widthDensity  数值越大每页横向水印越少
     * @param cover         是否覆盖
     * @return
     */

    public static boolean addWaterMark(String pdfUrl, String finalUrl, String waterMarkName,
                                       int fontsize, int heightDensity, int widthDensity) {
        return addWaterMark(pdfUrl, finalUrl, waterMarkName, 0.3f, fontsize, 30, heightDensity, widthDensity, true);
    }

    public static boolean addWaterMark(String pdfUrl, String pdfUrlWithMark, String waterMarkName,
                                       float opacity, int fontsize, int angle, int heightDensity, int widthDensity, boolean cover) {
        if (!cover) {
            File file = new File(pdfUrlWithMark);
            if (file.exists()) {
                return true;
            }
        }
        File file = new File(pdfUrl);
        if (!file.exists()) {
            return false;
        }

        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            int interval = -5;
            reader = new PdfReader(pdfUrl);
            stamper = new PdfStamper(reader, new FileOutputStream(pdfUrlWithMark));
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            Rectangle pageRect = null;
            PdfGState gs = new PdfGState();
            //这里是透明度设置
            gs.setFillOpacity(opacity);
            //这里是条纹不透明度
            gs.setStrokeOpacity(0.2f);
            int total = reader.getNumberOfPages() + 1;

            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH = 0;
            int textW = 0;
            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            //字符串的高,   只和字体有关
            textH = metrics.getHeight();
            //字符串的宽
            textW = metrics.stringWidth(label.getText());
            PdfContentByte under;
            //循环PDF，每页添加水印
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);  //在内容上方添加水印
                //under = stamper.getUnderContent(i);  //在内容下方添加水印
                under.saveState();
                under.setGState(gs);
                under.beginText();
                //under.setColorFill(BaseColor.PINK);  //添加文字颜色  不能动态改变 放弃使用
                under.setFontAndSize(base, fontsize); //这里是水印字体大小
                for (int height = textH; height < pageRect.getHeight() * 2; height = height + textH * heightDensity) {
                    for (int width = textW; width < pageRect.getWidth() * 1.5 + textW; width = width + textW * widthDensity) {
                        // rotation:倾斜角度
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, angle);
                    }
                }
                //添加水印文字
                under.endText();
            }
            return true;
        } catch (Exception e) {
            log.error("添加水印失败！错误信息为: ", e);
            return false;
        } finally {
            //关闭流
            if (stamper != null) {
                try {
                    stamper.close();
                } catch (Exception e) {
                    log.error("关闭stamper失败: ", e);
                }
            }
            if (reader != null) {
                reader.close();
            }
        }
    }
}
